/*
 Author:du
 Time:2017.11.8
*/

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
using System.Text;

namespace FutureCoreEditor
{
    /// <summary>
    /// Zip 压缩帮助类
    /// </summary>
    public class GZipHelper
    {
        private static int Level = 5;

        public class ZipRecursiver
        {
            private string folderToZip;
            private ZipOutputStream zipStream;
            private string startFolderName;

            public ZipRecursiver(string f, ZipOutputStream z)
            {
                folderToZip = f;
                zipStream = z;
                startFolderName = Path.GetFileName(folderToZip);
            }

            public bool Zip()
            {
                return Recursive(folderToZip);
            }

            private bool Recursive(string currentFolderToZip)
            {
                bool result = true;
                string[] folders, files;
                ZipEntry ent = null;
                FileStream fs = null;
                Crc32 crc = new Crc32();
                try
                {
                    string path = currentFolderToZip.Replace(folderToZip, startFolderName) + "/";
                    ent = new ZipEntry(path);
                    zipStream.PutNextEntry(ent);
                    zipStream.Flush();

                    files = Directory.GetFiles(currentFolderToZip);
                    foreach (string file in files)
                    {
                        if (Path.GetExtension(file).Equals(".meta"))
                            continue;
                        fs = File.OpenRead(file);

                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        ent = new ZipEntry(path + Path.GetFileName(file));
                        ent.DateTime = DateTime.Now;
                        ent.Size = fs.Length;
                        fs.Close();

                        crc.Reset();
                        crc.Update(buffer);

                        ent.Crc = crc.Value;
                        zipStream.PutNextEntry(ent);
                        zipStream.Write(buffer, 0, buffer.Length);
                    }

                }
                catch
                {
                    result = false;
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                        fs.Dispose();
                    }
                    if (ent != null)
                    {
                        ent = null;
                    }
                    GC.Collect();
                    GC.Collect(1);
                }

                folders = Directory.GetDirectories(currentFolderToZip);
                foreach (string folder in folders)
                    if (!Recursive(folder))
                        return false;

                return result;
            }
        }

        /// <summary>
        /// 设置编码
        /// </summary>
        private static void SetCode()
        {
            // 需要注意的是 默认编码如果有中文的文件名或目录将会乱码，甚至解压的数据出错。所以设置一下支持中文的编码
            ZipConstants.DefaultCodePage = Encoding.UTF8.CodePage;
        }

        /// <summary>
        /// 压缩所有到Zip
        /// </summary>
        public static bool ZipAll(string folderToZip, string zipedFile)
        {
            SetCode();

            bool result = false;
            if (!Directory.Exists(folderToZip))
                return result;

            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(Level);

            ZipRecursiver zr = new ZipRecursiver(folderToZip, zipStream);
            result = zr.Zip();

            zipStream.Finish();
            zipStream.Close();

            return result;
        }

        /// <summary>
        /// 解压压缩文件到指定目录
        /// </summary>
        /// <param name="fileToUnZip">待解压的文件</param>
        /// <param name="zipedFolder">指定解压目标目录</param>
        /// <returns>结果</returns>
        public static bool UnZip(string fileToUnZip, string zipedFolder)
        {
            bool result = UnZip(fileToUnZip, zipedFolder, null);
            return result;
        }

        /// <summary>
        /// 解压压缩文件到指定目录
        /// </summary>
        /// <param name="fileToUnZip">待解压的文件</param>
        /// <param name="zipedFolder">指定解压目标目录</param>
        /// <param name="password">密码</param>
        /// <returns>结果</returns>
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            SetCode();

            bool result = true;
            FileStream fs = null;
            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            string fileName;

            if (!File.Exists(fileToUnZip))
            {
                return false;
            }
            if (!Directory.Exists(zipedFolder))
            {
                Directory.CreateDirectory(zipedFolder);
            }

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('\\', '/');

                        if (fileName.EndsWith("/"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        fs = File.Create(fileName);
                        int size = 2048;
                        byte[] data = new byte[size];
                        while (true)
                        {
                            size = zipStream.Read(data, 0, data.Length);
                            if (size > 0)
                                fs.Write(data, 0, size);
                            else
                                break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DebugUtil.LogError(e);
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }
    }
}